import { connectDB, writeData, readTableData } from './indexDB'

/**
 * Store 存储约束规则数据
 */

const TABLE_NAME = 'TagsList'
const LAST_TAGS_NAME = 'LastTagsName'
/**
 * 数据库名
 */
const DB_NAME = 'ModXmlEditor'

/**
 * 保存约束规则
 * @param {约束规则名} name 
 * @param {约束规则对象} tagsItem 
 */
const saveTags = (name, tagsItem) => {
  return connectDB(DB_NAME, TABLE_NAME).then(db => {
    return writeData(db, TABLE_NAME, name, tagsItem)
  })
}

/**
 * 读取约束规则列表
 */
const getTagsList = () => {
  return connectDB(DB_NAME, TABLE_NAME).then(db => {
    return readTableData(db, TABLE_NAME).then((table)=>{
      if(table.length===0){
        return []
      }
      return table
    })
  })
}

/**
 * 保存最近一次应用的约束规则名
 * @param {约束规则名} name 
 */
export const saveLastTagsName = (name) => {
  localStorage.setItem(LAST_TAGS_NAME, name)
}

/**
 * 获取最近一次应用的约束规则名
 */
const getLastTagsName = () => {
  return localStorage.getItem(LAST_TAGS_NAME)
}

export default {
  saveTags,
  getTagsList,
  saveLastTagsName,
  getLastTagsName
}
